<template>
    <div>
        <div :class='$style.shares'>
            <!-- <a-descriptions size='small' :column='4' bordered>
                <template v-for='(task, index) in taskList' :key='index'>
                    <a-descriptions-item label='股票名称'>{{task.code_name}}</a-descriptions-item>
                    <a-descriptions-item label='策略名称'>{{task.strategy_name}}</a-descriptions-item>
                    <a-descriptions-item label='参数'>
                        <div :class='$style.param'>
                            <template v-for='(v, k) in task.params'>
                                <div :class='$style.item'>
                                    <div :class='$style.paramName'>{{k}}</div>
                                    <div :class='$style.paramValue'>{{v}}</div>
                                </div>
                            </template>
                        </div>
                    </a-descriptions-item>
                    <a-descriptions-item label='进度'>
                        <a-progress size='small' status='active' :percent='task.progress' />
                    </a-descriptions-item>
                </template>
            </a-descriptions> -->
            <a-table bordered :pagination='false' :dataSource='taskList' :columns='sharesColumns'>
                <template #bodyCell='{ record, column }'>
                    <template v-if='column.dataIndex ==="params"'>
                        <div :class='$style.param'>
                            <template v-for='(v, k) in record.params'>
                                <div :class='$style.item'>
                                    <div :class='$style.paramName'>{{k}}</div>
                                    <div :class='$style.paramValue'>{{v}}</div>
                                </div>
                            </template>
                        </div>
                    </template>
                    <template v-else-if='column.dataIndex ==="progress"'>
                        <a-progress size='small' status='active' :percent='record.progress' />
                    </template>
                </template>
            </a-table>
        </div>

    <div :class='$style.backTestSet'>
        <div style='flex:1'>设置： {{backTestSet.start_date}} 到 {{backTestSet.end_date}}， {{backTestSet.cash}}&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;状态：<a-tag>{{backTestSet.status_text}}</a-tag><!-- <XBackTestStatus :status='backTestSet.status' /> --></div>
        <router-link v-if='testStatus == 1' :to='"/strategy/follow/setting/" + packageId'>
            <a-button type='primary'>
                <span style="font-size:12px">开始跟踪</span>
            </a-button>
        </router-link>
    </div>
    </div>

    <div :class='$style.detailContainer'>
        <BackTestDetail :profitSummary='profitSummary' :transactionDetail='transactionDetail' :position='position' :strategyProfit='strategyProfit' :benchmarkProfit='benchmarkProfit' @change='selectedTap' />
    </div>

</template>

<script lang='ts' setup>
    import { useRoute } from 'vue-router'
    import { combinationBackTestTaskDetailApi, combinationBackTestTaskProgressApi, profitSummaryApi, transactionDetailApi, positionApi, strategyProfitApi, benchmarkProfitApi } from '@/api/combinationBackTest'
    import BackTestDetail from '../BackTestDetail/index.vue'
    import { onBeforeUnmount, onMounted, reactive, ref } from 'vue'
    import { TRANS } from '@/constant'
import { message } from 'ant-design-vue'
    
    const route = useRoute()

    const sharesColumns:any[] = [
        {title : '股票名称', dataIndex : 'code_name', align : 'center'},
        {title : '策略名称', dataIndex : 'strategy_name', align : 'center'},
        {title : '参数', dataIndex : 'params', align : 'center'},
        {title : '进度', dataIndex : 'progress', align : 'center'},
    ]
    const sharesDataSource:any[] = []

    const packageId = route.params.id
    let timer = null
    const backTestSet = reactive({
        start_date : '---',
        end_date : '---',
        cash : '---',
        status : '',
        status_text : ''
    })
    const taskList = reactive<any[]>([])

    const profitSummary = ref<any>(null)
    const transactionDetail = ref<any>(null)
    const position = ref<any>(null)
    const strategyProfit = ref<any>(null)
    const benchmarkProfit = ref<any>(null)

    let testStatus = ref(0)
    
    let getProfitSummaryCount = ref(0)

    function getProfitSummary() {
        profitSummaryApi({package_id : packageId, is_batch : 1}).then(res => { //获取收益概述
            const data = res.data

            const profitSummaryTemp = {
                status : data.status,
                statusText : '',
                summary : [],
                chart : {
                    xAxis : [],
                    series : [[], []],

                }
            }

            
            backTestSet.status = data.status
            backTestSet.status_text = data.status_text

            if(!res.success || data.status != 3) {
                if(data.status == 2 && getProfitSummaryCount.value < 3) {
                    getProfitSummaryCount.value ++
                    setTimeout(() => {
                        getProfitSummary()
                    }, 3000);
                }else {
                    profitSummaryTemp.statusText = res.message
                    profitSummary.value = profitSummaryTemp
                    message.error(res.message)
                }
                
                return
            }

            backTestSet.cash = data.cash

            

            for(let k in data) {
                if(['benchmark_cum_returns', 'strategy_cum_returns', 'status', 'status_text'].includes(k)) continue
                profitSummaryTemp.summary.push({name : TRANS[k], value : data[k]})
            }

            for(let time in data.benchmark_cum_returns) {
                profitSummaryTemp.chart.series[0].push([time, data.benchmark_cum_returns[time]])
            } 

            for(let time in data.strategy_cum_returns) {
                profitSummaryTemp.chart.series[1].push([time, data.strategy_cum_returns[time]])
            } 

            profitSummaryTemp.chart.xAxis.push(...Object.keys(data.strategy_cum_returns))

            profitSummary.value = profitSummaryTemp

        })
    }

    

    async function selectedTap(key) {
        if(testStatus.value != 1) return
        if(key == 2) {
            if(transactionDetail.value == null) {
                const res = await transactionDetailApi({package_id : packageId})
                const data = res.data
                if(!res.success ) {
                    transactionDetail.value = []
                    message.error(res.message)
                    return
                }else {
                    transactionDetail.value = data
                }
                
                
            }
        }else if(key == 3) {
            if(position.value == null) {
                const res = await positionApi({package_id : packageId})
                const data = res.data
                if(!res.success) {
                    position.value = []
                    message.error(res.message)
                    return
                }else {
                    position.value = data
                }
            }
        }else if(key == 4) {
            if(strategyProfit.value == null) {
                const res = await strategyProfitApi({package_id : packageId})
                const data = res.data
                if(!res.success) {
                    strategyProfit.value = []
                    message.error(res.message)
                    return
                }else {
                    strategyProfit.value = data
                }
            }
        }else if(key == 5) {
            if(benchmarkProfit.value == null) {
                const res = await benchmarkProfitApi({package_id : packageId})
                const data = res.data
                if(!res.success) {
                    benchmarkProfit.value = []
                    message.error(res.message)
                    return
                }else {
                    benchmarkProfit.value = data
                }
            }
        }
    }

    combinationBackTestTaskDetailApi({package_id : packageId}).then(data => { //获取顶部的
        backTestSet.start_date = data.start_date
        backTestSet.end_date = data.end_date
        taskList.push(...data.task_list.map(task => {
            task.progress = 0
            return task
        }))

        timer = setInterval(() => {
            combinationBackTestTaskProgressApi({package_id : packageId}).then(data => {
                if(data.every(v => v.run_status == 5)) { //如果所有都为5了，则停止
                    testStatus.value = 1
                    clearInterval(timer)
                    getProfitSummary()
                }
                for(let i = 0; i < taskList.length; i ++) {
                    taskList[i].progress = data[i].run_status * 20
                }
            })
        }, 2000)
    })

    onBeforeUnmount(() => {
        clearInterval(timer)
    })

    

</script>


<style lang='scss' module>
    .backTestSet{
        padding: $space;
        font-size: 14px;
        display: flex;
        align-items: center;
    }

    .detailContainer{
        //border-top: 1px solid #f0f0f0;
    }

    .shares{
        text-align: center;
        padding: 0 $space 0 $space;
        :global(.ant-descriptions-item-label) {
            text-align: center;
        }
    }
    .param {
        text-align: center;
        display: inline-flex;
        gap: 10px;
        .paramName{
            font-size: 12px;
            color: #8c8c8c;
        }
        .paramValue{
            font-size: 14px;
            font-weight: 700;
            color: #666;
        }
    }
    
</style>